package cn.easier.activity.console.controller;

import cn.easier.activity.console.repository.OptionMessageRepository;
import cn.easier.activity.console.repository.QuestionnaireAnswerMessageRepository;
import cn.easier.activity.console.repository.QuestionnaireMessageRepository;
import cn.easier.activity.web.entity.OptionMessage;
import cn.easier.activity.web.entity.QuestionnaireAnswersMessage;
import cn.easier.activity.web.entity.QuestionnaireMessage;
import cn.easier.club.base.dto.PageInfo;
import cn.easier.club.base.dto.ResultInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 问卷内容
 */
@RestController
@RequestMapping("/questionnaire")
public class ActivityQuestionnaireController extends BaseController {

    private Logger log = LoggerFactory.getLogger(ActivityQuestionnaireController.class);

    private final QuestionnaireMessageRepository questionnaireMessageRepository;
    private final QuestionnaireAnswerMessageRepository answerRepository;
    private final OptionMessageRepository optionMessageRepository;

    public ActivityQuestionnaireController(QuestionnaireMessageRepository questionnaireMessageRepository, QuestionnaireAnswerMessageRepository answerRepository, OptionMessageRepository optionMessageRepository) {
        this.questionnaireMessageRepository = questionnaireMessageRepository;
        this.answerRepository = answerRepository;
        this.optionMessageRepository = optionMessageRepository;
    }

    @GetMapping("/answers")
    public ResultInfo get(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "activityId", required = false) Integer activityId,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "phoneNum", required = false) String phoneNum) {
        AtomicReference<String> username = new AtomicReference<>();
        ifNotAdmin(username::set);
        if (StringUtils.isBlank(title)) {
            title = null;
        } else {
            title = "%" + title + "%";
        }
        if (StringUtils.isBlank(phoneNum)) {
            phoneNum = null;
        }
        page--;
        Page<Object[]> answerPage = answerRepository.findAnswerList(username.get(), activityId, title, phoneNum, new PageRequest(page, size, Sort.Direction.DESC, "create_time"));
        List<Map<String, String>> list = new ArrayList<>();
        for (Object[] objects : answerPage) {
            HashMap<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(objects[0]));
            map.put("activityName", (String) objects[1]);
            map.put("question", (String) objects[2]);
            map.put("answer", (String) objects[3]);
            map.put("phoneNum", String.valueOf(objects[4]));
            map.put("createTime", DateFormatUtils.format((Date) objects[5], "yyyy-MM-dd HH:mm:ss"));
            list.add(map);
        }
        PageInfo<Map<String, String>> pageInfo = new PageInfo<>(list, (int) answerPage.getTotalElements(), size, answerPage.getTotalPages(), page);
        return new ResultInfo(String.valueOf(HttpStatus.SC_OK), "保存成功", pageInfo);
    }

    @GetMapping("/answersQuestionnaire")
    public ResultInfo getQuestionnaireMessage(
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "activityId", required = false) Integer activityId,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "answer", required = false) String answer) {
        AtomicReference<String> username = new AtomicReference<>();
        ifNotAdmin(username::set);
        List<Long> idList = new ArrayList<>();
        List<Integer> questionnaireIdList = new ArrayList<>();
        List<Long> questionnaireIdList1 = new ArrayList<>();
        if (StringUtils.isBlank(title)) {
            title = null;
        } else {
            title = "%" + title + "%";
        }
        page--;
        Page<Object[]> answerPage;
        List<QuestionnaireMessage> investigation = questionnaireMessageRepository.findByType("investigation");
        for (QuestionnaireMessage message : investigation) {
            questionnaireIdList.add(message.getId().intValue());
            questionnaireIdList1.add(message.getId());
        }
        if (StringUtils.isNotBlank(answer)) {
            List<QuestionnaireAnswersMessage> byAnswersMessage = answerRepository.findByAnswersMessageAndQuestionnaireMessageIdIn(answer, questionnaireIdList);
            List<OptionMessage> optionMessageList = optionMessageRepository.findByOptionNameAndQuestionnaireMessageIdIn(answer, questionnaireIdList1);
            if (CollectionUtils.isEmpty(optionMessageList)) {
                idList.clear();
            } else {
                for (OptionMessage optionMessage : optionMessageList) {
                    idList.add(optionMessage.getId());
                }
            }
            //username.get(),
            if (CollectionUtils.isNotEmpty(idList)) {
                if (CollectionUtils.isEmpty(byAnswersMessage)) {
                    answerPage = answerRepository.findAnswersQuestionnaireList1(username.get(), activityId, title,idList, new PageRequest(page, size, Sort.Direction.DESC, "create_time"));
                }else {
                    answerPage = answerRepository.findAnswersQuestionnaireList(username.get(), activityId, title, answer,idList, new PageRequest(page, size, Sort.Direction.DESC, "create_time"));
                }
            } else {
                if (CollectionUtils.isEmpty(byAnswersMessage)) {
                    answer = "ergergyhyjyuj";
                }
                answerPage = answerRepository.findAnswersQuestionnaire(username.get(), activityId, title, answer, new PageRequest(page, size, Sort.Direction.DESC, "create_time"));
            }
        } else {
            answerPage = answerRepository.findAnswersQuestionnaire(username.get(), activityId, title, null, new PageRequest(page, size, Sort.Direction.DESC, "create_time"));
        }
        List<Map<String, String>> list = new ArrayList<>();
        for (Object[] objects : answerPage) {
            HashMap<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(objects[0]));
            map.put("activityName", (String) objects[1]);
            map.put("question", (String) objects[2]);
            if (objects[3] == null || StringUtils.isBlank(objects[3].toString())){
                Optional<OptionMessage> byId = optionMessageRepository.findById(Long.valueOf(objects[4].toString()));
                if (byId.isPresent()) {
                    map.put("answer", byId.get().getOptionName());
                } else {
                    map.put("answer", "");
                }
            } else {
                map.put("answer", (String) objects[3]);
            }
            map.put("createTime", DateFormatUtils.format((Date) objects[5], "yyyy-MM-dd HH:mm:ss"));
            list.add(map);
        }
        PageInfo<Map<String, String>> pageInfo = new PageInfo<>(list, (int) answerPage.getTotalElements(), size, answerPage.getTotalPages(), page);
        return new ResultInfo(String.valueOf(HttpStatus.SC_OK), "保存成功", pageInfo);
    }
}
